package com.itheima.config;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.util.List;

/**
 * MyBatis的自动配置类
 * @author wuhaohua
 */
@AutoConfiguration//表示当前类是一个自动配置类
public class MyBatisAutoConfig {

    /**
     * 自动注入SqlSessionFactoryBean对象
     * @param dataSource 需要连接的数据源
     * @return
     */
    @Bean
    public SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    /**
     * 自动注入MapperScannerConfigurer对象
     * @param beanFactory 由spring-boot-starter提供的用于获取启动类所在的包名
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(BeanFactory beanFactory) {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();

        // 设置要扫描的包：启动类所在的包及其子包（由spring-boot-starter提供方法）
        List<String> packages = AutoConfigurationPackages.get(beanFactory);
        String p = packages.get(0);
        mapperScannerConfigurer.setBasePackage(p);

        // 设置要扫描的注解：Mapper注解
        mapperScannerConfigurer.setAnnotationClass(Mapper.class);

        return mapperScannerConfigurer;
    }
}
